<template>
  <div class="login">
    <div class="form shadow">
      <h1 style="font-size:30px">煌上煌员工之声</h1>
      <el-form v-if="registerType" :model="ruleForm" status-icon :rules="rules" ref="loginFrom" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="userName">
          <el-input type="text" v-model.trim="ruleForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input type="password" v-model="ruleForm.passWord" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="randomCode">
          <div class="imgCode">
            <el-input type="text" v-model="ruleForm.randomCode" autocomplete="off"></el-input>
            <span @click="getImg" class="img" v-html="imgCodeSrc"></span>
          </div>
        </el-form-item>
        <div class="form-btns">
          <el-form-item>
            <el-button type="primary" @click="submitForm">登录</el-button>
            <el-button @click="chiceType(false)">加盟商注册</el-button>
          </el-form-item>
        </div>
      </el-form>
      <el-form v-else :model="ruleForm" status-icon :rules="rules" ref="registerFrom" label-width="100px" class="demo-ruleForm">
        <el-form-item label="姓名" prop="realName">
          <el-input type="text" v-model.trim="ruleForm.realName" placeholder="请输入真实姓名" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="userNamePhone">
          <el-input type="text" v-model.trim="ruleForm.userName" placeholder="请输入手机号" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺编码" prop="storeId">
          <el-input type="text" v-model.trim="ruleForm.storeId" placeholder="请输入店铺编码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input type="password" v-model="ruleForm.passWord" placeholder="请输入密码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="newPass2">
          <el-input type="password" v-model="ruleForm.newPass2" placeholder="确定密码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="sms">
          <div class="imgCode">
            <el-input type="text" v-model="ruleForm.sms" autocomplete="off"></el-input>
            <el-button @click="checkSms" :disabled="btnType" style="margin-left:40px;width:160px">{{btnText}}</el-button>
          </div>
        </el-form-item>
        <div class="form-btns">
          <el-form-item>
            <el-button @click="chiceType(true)">有账号去登录</el-button>
            <el-button type="primary" @click="registerFn">注册</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { useRouter } from 'vue-router';
import { ref, reactive,computed } from 'vue';
import store from 'src/store';
import {
    login, getImgVerify, getVerifySms, register
} from 'src/plugins/http/server/sys/user';
import { msgFn } from 'src/utils';
import md5 from 'md5';

export default {
    setup() {
        localStorage.clear();
        const userInfo = computed(() => store.state.userInfo);
        const router = useRouter();
        if (userInfo.value.id){
            router.replace('/articleList/1');
        }
        let countdown = 60;
        const registerType = ref(true);
        const loginFrom = ref();
        const registerFrom = ref();
        const imgCodeSrc = ref();
        const ruleForm = reactive({
            'userName': '',
            'realName': '',
            'newPass2': '',
            'sms': '',
            'storeId':'',
            'passWord': '',
            'randomCode': ''
        });
        const btnType = ref(false);
        const btnText = ref('获取验证码');
        let newPass2 = (rule: string, value: string, callback: (e?: any) => void) => {
            if (!ruleForm.newPass2) {
                callback(new Error('请确认密码'));
            } else if (ruleForm.newPass2 !== ruleForm.passWord) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        let validatePhone = (rule: string, value: string, callback: (e?: any) => void) => {
            if (ruleForm.userName === '') {
                callback(new Error('请输入手机号'));
            } else if (!UtilTools.isPhoneNum(ruleForm.userName)) {
                callback(new Error('请输入正确的手机号'));
            } else {
                callback();
            }
        };
        let validateStoreId = (rule: string, value: string, callback: (e?: any) => void) => {
            let reg = /^[c|C]\d{5}/g;
            if (ruleForm.storeId === '') {
                callback(new Error('请输入店铺编码'));
            } else if (!reg.test(ruleForm.storeId)) {
                callback(new Error('请输入正确的店铺编码'));
            } else {
                callback();
            }
        };
        const rules = {
            'userNamePhone': [{ 'required': true, 'validator': validatePhone, 'trigger': 'blur' }],
            'userName': [
                {
                    'required': true,
                    'message': '用户名不能为空',
                    'trigger': 'blur'
                }
            ],
            'realName': [
                {
                    'required': true,
                    'message': '真实姓名不能为空',
                    'trigger': 'blur'
                }
            ],
            'passWord': [
                {
                    'required': true,
                    'message': '请输入密码',
                    'trigger': 'blur'
                }
            ],
            'sms': [
                {
                    'required': true,
                    'message': '请输入验证码',
                    'trigger': 'blur'
                }
            ],
            'storeId': [
                {
                    'required': true, 'validator': validateStoreId, 'trigger': 'blur'
                }
            ],
            'newPass2': [{'required': true,'validator': newPass2, 'trigger': 'blur' }],
            'randomCode': [
                {
                    'required': true,
                    'message': '请输入验证码',
                    'trigger': 'blur'
                }
            ]
        };
        const Logining = (myRuleForm: loginObj, errFn: (e: string) => void) => {
            const data = {
                ...myRuleForm,
                'passWord': md5(myRuleForm.passWord)
            };
            login({ data })
                .then((res: any) => {
                    store.commit('_userInfo', res.data);
                    msgFn('登录成功', 'success');
                    setTimeout(() => {
                        router.push('/articleList/1');
                    }, 1001);
                })
                .catch((e: any) => {
                    if (errFn) {
                        errFn(e);
                    }
                });
        };

        const getImg = () => {
            const opts = {
                'method': 'get',
                'isLoading': '0'
            };
            const data = {
                'width': 200,
                'height': 40,
                'time': Date.now().toString()
            };
            getImgVerify({ opts, data })
                .then((res: any) => {
                    imgCodeSrc.value = res.data.img;
                })
                .catch((e: any) => {
                    msgFn(e);
                });
        };
        const resetData = () => {
            ruleForm.userName = '';
            ruleForm.passWord = '';
            ruleForm.sms = '';
            ruleForm.realName = '';
            ruleForm.randomCode = '';
            ruleForm.storeId = '';
            ruleForm.newPass2 = '';
        };
        const chiceType = (type: boolean) => {
            registerType.value = type;
            resetData();
        };
        const registerFn = () => {
            registerFrom.value.validate((valid: boolean) => {
                if (valid) {
                    const opts = {
                        'method': 'post',
                        'isLoading': '1'
                    };
                    const data = {
                        'userName': ruleForm.userName,
                        'passWord': md5(ruleForm.passWord),
                        'sms': ruleForm.sms,
                        'storeId': ruleForm.storeId.toUpperCase(),
                        'realName': ruleForm.realName
                    };
                    register({ opts, data })
                        .then((res: any) => {
                            msgFn('注册成功', 'success');
                            registerType.value = true;
                            resetData();
                        })
                        .catch(e => {
                            msgFn(e);
                        });
                } else {
                    console.error('error submit!!');
                    return false;
                }
            });
        };

        const settime = () => {
            if (countdown === 0) {
                btnType.value = false;
                btnText.value = '获取验证码';
                countdown = 60;
                return;
            }
            btnType.value = true;
            btnText.value = `重新发送(${countdown})`;
            countdown--;
            setTimeout(() => {
                settime();
            }, 1000);
        };
        const checkSms = () => {
            let type = UtilTools.isPhoneNum(ruleForm.userName);
            if (type && !btnType.value) {
                const opts = {
                    'method': 'post',
                    'isLoading': '0'
                };
                const data = {
                    'phone': ruleForm.userName
                };
                getVerifySms({ opts, data })
                    .then((res: any) => {
                        msgFn('验证码发送成功', 'success');
                    })
                    .catch(e => {
                        msgFn(e);
                    });
                settime();
            } else {
                msgFn('请输入正确的手机号码');
            }
        };
        const submitForm = () => {
            loginFrom.value.validate((valid: boolean) => {
                if (valid) {
                    Logining(ruleForm, e => {
                        msgFn(e || '服务器异常，登录失败');
                        getImg();
                    });
                } else {
                    console.error('error submit!!');
                    return false;
                }
            });
        };
        const resetForm = () => {
            registerFrom.value.resetFields();
        };
        getImg();

        return {
            Logining,
            getImg,
            submitForm,
            resetForm,
            chiceType,
            settime,
            registerFn,
            checkSms,
            loginFrom,
            registerFrom,
            ruleForm,
            rules,
            imgCodeSrc,
            registerType,
            btnText,
            btnType
        };
    }
};
</script>

<style scoped lang="less">
@import '~@/assets/less/login';
</style>
